package com.gxa.interceptor;

import com.gxa.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author Tian同學
 * @Date 2020/10/1 20:17
 * @Version 1.0
 */
@RestController
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        // 这里是专门用于处理前端ajax请求时带有自定义请求头
        if(request.getMethod().equals("OPTIONS")){
            // 设置跨域的处理，  此类中使用@CrossOrigin没有起作用，是一个遗憾
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type,accessToken");
            response.setHeader("Access-Control-Expose-Headers", "*");
            // 一定要给前端返回一个200字符串的值
            PrintWriter writer = response.getWriter();
            writer.write("200");
            writer.flush();
            writer.close();
        }else{   // else 表示除了OPTIONS类型请求之外的其它请求: GET/POST/DELETE/PUT
             /*  TODO: + 说明：
  如果代码中有该标识，说明在标识处有功能代码待编写，待实现的功能在说明中会简略说明。

        FIXME: + 说明：
  如果代码中有该标识，说明标识处代码需要修正，甚至代码是错误的，不能工作，需要修复，如何修正会在说明中简略说明。
：*/
            JWTUtil util = new JWTUtil();
            String jwt = request.getHeader("accessToken");
            System.out.println("jwt:"+jwt);
            try {
                if (jwt == null) {
                    System.out.println("请求头为空, 验证失败");
                } else {
                    Claims c;
                    c = util.parseJWT(jwt);
                    System.out.println("id为" + c.get("id") + "的用户已是登录状态");
                    return true;
                }
                System.out.println("token解析错误，验证失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
